#!/bin/sh

if [ -z "$1" ]; then
	echo "Usage $0 patch_count"
	exit
fi

set -x -e -u

patch_count=$1
in_dir=../training/tumor
out_dir=../PATCH

for img in "$in_dir"/*.tif
do
	# img like ../training/tumor/tumor_xxxx.tif
	# idx like tumor_xxx
	idx=$(basename -s .tif "$img")
	xml_file=$in_dir/../lesion_annotations/$idx.xml
	json_file=$out_dir/annotation/$idx.json
	tissue_mask=$out_dir/tissue_mask/$idx.npy
	tumor_mask=$out_dir/tumor_mask/$idx.npy
	tumor_spot=$out_dir/tumor_spot/$idx.spot

	[ -f "$json_file" ] || \
	python ./camelyon16/bin/camelyon16xml2json.py "$xml_file" "$json_file"
	[ -f "$tissue_mask" ] || \
	python ./camelyon16/bin/tissue_mask.py --level 6 "$img"  "$tissue_mask"
	[ -f "$tumor_mask" ] || \
	python ./camelyon16/bin/tumor_mask.py  --level 6 "$img"  "$json_file" "$tumor_mask"

	rm -f "$tumor_spot"
	python ./camelyon16/bin/sampled_spot_gen.py "$tumor_mask"  "$tumor_spot"  "$patch_count"

	python ./camelyon16/bin/patch_gen.py --level 0 --num_process 32 --patch_size 224 "$img" "$tumor_spot"  $out_dir/training_patch/tumor/"$idx"/
done

find tumor -type f -name '*.jpg' | tee tumor.list
wc -l tumor.list

sed -i "s@\"data_path_train\".*@\"data_path_train\": \"$out_dir/training_patch\",@g" camelyon16/configs/cnn.json
sed -i "s@\"data_path_valid\".*@\"data_path_valid\": \"$out_dir/training_patch\",@g" camelyon16/configs/cnn.json

cat camelyon16/configs/cnn.json
